package park.gz.com.parkingfee.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import park.gz.com.parkingfee.R;
import park.gz.com.parkingfee.activity.FeeDetailActivity;
import park.gz.com.parkingfee.activity.MainActivity;
import park.gz.com.parkingfee.activity.MyAppcation;
import park.gz.com.parkingfee.adapter.SelectListAdapter;
import park.gz.com.parkingfee.bean.FeeHistory;
import park.gz.com.parkingfee.bean.UserBean;
import park.gz.com.parkingfee.until.CustomDatePicker;
import park.gz.com.parkingfee.until.GetImei;
import park.gz.com.parkingfee.until.ShareUtil;

/**
 * Created by Administrator on 2017-03-15.
 */

public class QueryfeeFragment extends BaseFragment implements SelectListAdapter.OnItemClickListener, PopupWindow.OnDismissListener {

    @Bind(R.id.rl_title)
    RelativeLayout rlTitle;
    @Bind(R.id.tx_carnumber)
    TextView txCarnumber;
    @Bind(R.id.input_carnumber)
    EditText inputCarnumber;
    @Bind(R.id.rl_carnum)
    LinearLayout rlCarnum;
    @Bind(R.id.ly_query)
    LinearLayout lyQuery;
    @Bind(R.id.tx_admin)
    TextView txAdmin;
    @Bind(R.id.tx_choiceadmin)
    TextView txChoiceadmin;
    @Bind(R.id.tx_starttime)
    TextView txStarttime;
    @Bind(R.id.tx_endtime)
    TextView txEndtime;
    @Bind(R.id.in_time)
    LinearLayout intime;
    @Bind(R.id.recyckerview)
    RecyclerView recyckerview;
    @Bind(R.id.rl_bottom)
    RelativeLayout rlBottom;
    @Bind(R.id.ly_recyclertitle)
    LinearLayout lyRecyclertitle;
    @Bind(R.id.outapplication)
    TextView outapplication;
    @Bind(R.id.btn_query)
    Button btnQuery;
    @Bind(R.id.car_count)
    TextView carCount;
    @Bind(R.id.fee)
    TextView fee;
    @Bind(R.id.fact_fee)
    TextView factFee;
    @Bind(R.id.tx_tishi)
    TextView txTishi;
    @Bind(R.id.ly_tishi)
    LinearLayout lyTishi;
    private CustomDatePicker customDatePicker1, customDatePicker2;

    private MyAdapter adapter;
    private List<FeeHistory> feeHistoryList;
    private List<UserBean> userBeanList;
    private PopupWindow mSelectWindow;
    private LayoutInflater mInflater;
    private SelectListAdapter selectadapter;


    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_queryfee, container, false);
        ButterKnife.bind(this, view);
        initDatePicker();
        feeHistoryList = new ArrayList<FeeHistory>();
        userBeanList = new ArrayList<UserBean>();
        lyTishi.setVisibility(View.VISIBLE);
        txTishi.setText("~筛选上面☝条件进行查找~");
        recyckerview.setVisibility(View.GONE);
        return view;
    }

    @Override
    protected void iniView() {
        LogUtil.i("iniview");
        mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        RecyclerView.LayoutManager lm = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyckerview.setLayoutManager(lm);
        try {
            userBeanList.clear();
            userBeanList.addAll(UserBean.parse(new JSONArray(ShareUtil.getstringvalue(getActivity(), MyAppcation.userInfo))));
            UserBean user = new UserBean();
            user.setId("0");
            user.setUpdated_at("");
            user.setCreated_at("");
            user.setPassword("");
            user.setStatus("");
            user.setUsertype("");
            user.setLogin("全部");
            userBeanList.add(0,user);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void iniData() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.tx_starttime, R.id.tx_endtime, R.id.btn_query, R.id.tx_choiceadmin, R.id.outapplication})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tx_starttime:
                customDatePicker1.show(txStarttime.getText().toString());
                break;
            case R.id.tx_endtime:
                customDatePicker2.show(txEndtime.getText().toString());
                break;
            case R.id.btn_query:
                SimpleDateFormat smdf = new SimpleDateFormat("yyyy-MM-dd ");
                Date start = null;
                Date end = null;
                try {
                    start = smdf.parse(txStarttime.getText().toString());
                    end = smdf.parse(txEndtime.getText().toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                long t = (end.getTime() - start.getTime()) / (3600 * 24 * 1000);
                if ((int) t > 61) {
                    Toast.makeText(getActivity(), "起始时间不能超越两个月", Toast.LENGTH_LONG).show();
                } else {
                    record_fee();
                }

                break;
            case R.id.tx_choiceadmin:
                onDownArrowClicked(txChoiceadmin);
                break;
            case R.id.outapplication:
                Intent intent = new Intent(getActivity(), MainActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onDismiss() {
        //txChoiceadmin.setBackgroundResource(R.drawable.arrow_down);
    }

    @Override
    public void onItemClicked(int position) {
        mSelectWindow.dismiss();
        txChoiceadmin.setText(userBeanList.get(position).getLogin() + "");
    }

    class MyAdapter extends RecyclerView.Adapter<MyHolder> {

        @Override
        public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View item = LayoutInflater.from(getActivity()).inflate(R.layout.queryfeeitem, parent, false);
            MyHolder myHolder = new MyHolder(item);
            return myHolder;
        }

        @Override
        public void onBindViewHolder(MyHolder holder, final int position) {
            holder.carnumber.setText(feeHistoryList.get(position).getCar_no());
            holder.factmoney.setText(feeHistoryList.get(position).getFact_fee());
            if ("".equals(feeHistoryList.get(position).getIn_time()) || feeHistoryList.get(position).getIn_time() == null || "null".equals(feeHistoryList.get(position).getIn_time())) {
                holder.intime.setText("");
            } else {
                String time = feeHistoryList.get(position).getIn_time().substring(0, feeHistoryList.get(position).getIn_time().trim().lastIndexOf(":"));
                holder.intime.setText(time.substring(time.indexOf("-") + 1, time.length()));
            }
            holder.longtime.setText(minConvertDayHourMin(Double.parseDouble(feeHistoryList.get(position).getParked_time())));
            holder.money.setText(feeHistoryList.get(position).getFee());
            holder.lyitem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), FeeDetailActivity.class);
                    intent.putExtra("feedetail",feeHistoryList.get(position));
                    startActivity(intent);
                }
            });

        }

        @Override
        public int getItemCount() {
            return feeHistoryList.size();
        }
    }

    class MyHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.carnumber)
        TextView carnumber;
        @Bind(R.id.intime)
        TextView intime;
        @Bind(R.id.longtime)
        TextView longtime;
        @Bind(R.id.money)
        TextView money;
        @Bind(R.id.fact_money)
        TextView factmoney;
        @Bind(R.id.ly_item)
        LinearLayout lyitem;


        public MyHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    private void initDatePicker() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String now = sdf.format(new Date());
        txStarttime.setText(now);
        txEndtime.setText(now);
        customDatePicker1 = new CustomDatePicker(getActivity(), new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                txStarttime.setText(time);
            }
        }, "1999-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker1.showSpecificTime(true); // 不显示时和分
        customDatePicker1.setIsLoop(false); // 不允许循环滚动

        customDatePicker2 = new CustomDatePicker(getActivity(), new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                txEndtime.setText(time);
            }
        }, "1999-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker2.showSpecificTime(true); // 不显示时和分
        customDatePicker2.setIsLoop(false); // 不允许循环滚动

    }

    public static String minConvertDayHourMin(Double min) {
        String html = "0分";
        if (min != null) {
            Double m = (Double) min;
            String format;
            Object[] array;
            Integer days = (int) (m / (60 * 24));
            Integer hours = (int) (m / (60) - days * 24);
            Integer minutes = (int) (m - hours * 60 - days * 24 * 60);
            if (days > 0) {
                format = "%1$,d天%2$,d时%3$,d分";
                array = new Object[]{days, hours, minutes};
            } else if (hours > 0) {
                format = "%1$,d时%2$,d分";
                array = new Object[]{hours, minutes};
            } else {
                format = "%1$,d分";
                array = new Object[]{minutes};
            }
            html = String.format(format, array);
        }
        return html;
    }

    private void record_fee() {

        String url = ShareUtil.getstringvalue(getActivity(),"baseurl") + "/api/v2/record_fee";
        RequestParams params = new RequestParams(url);
        params.addParameter("out_operator", txChoiceadmin.getText().toString().trim());//收费员
        params.addParameter("begin_time", txStarttime.getText().toString().trim());//进入时间
        params.addParameter("end_time", txEndtime.getText().toString().trim());//出场时间
        params.addParameter("controller_sn", GetImei.getphoneimei(getActivity()));//终端编号
        params.addParameter("car_no", inputCarnumber.getText().toString());
        params.addParameter("access_token",ShareUtil.getstringvalue(getActivity(),"access_token"));
        Log.e("duzhijuan", params + "");
        x.http().get(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.getString("ref"))) {//设备未注册
                        Toast.makeText(getActivity(), jsonObject.getString("msg"), Toast.LENGTH_LONG).show();
                    } else if ("0".equals(jsonObject.getString("ref"))) {//搜索成功
                        feeHistoryList.clear();
                        feeHistoryList.addAll(FeeHistory.parse(jsonObject.getJSONArray("result")));
                        if (feeHistoryList.size()>0){
                            recyckerview.setVisibility(View.VISIBLE);
                            lyTishi.setVisibility(View.GONE);
                        }else{
                            recyckerview.setVisibility(View.GONE);
                            lyTishi.setVisibility(View.VISIBLE);
                            txTishi.setText("~什么都没找到~");
                        }
                        if ("null".equals(jsonObject.getString("fee")) || "0".equals(jsonObject.getString("fee"))) {
                            fee.setText("应收:￥0.0");
                        } else {
                            fee.setText("应收:￥" + jsonObject.getString("fee"));
                        }

                        if ("null".equals(jsonObject.getString("fact_fee")) || "0".equals(jsonObject.getString("fact_fee"))) {
                            factFee.setText("实收:￥0.0");
                        } else {
                            factFee.setText("实收:￥" + jsonObject.getString("fact_fee"));
                        }
                        carCount.setText("合计:" + jsonObject.getString("car_count") + "辆");
                        adapter = new MyAdapter();
                        recyckerview.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                    } else {
                        Toast.makeText(getActivity(), jsonObject.getString("msg"), Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("my", "onError" + ex.toString());
                Toast.makeText(getActivity(),"请求失败,请确认您的服务是否有误",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.e("my", "onCancelled" + cex.toString());
                Toast.makeText(getActivity(),"请求失败,请确认您的服务是否有误",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                Log.e("my", "onFinished");
            }

        });
    }

    public void onDownArrowClicked(View view) {
        if (userBeanList.size() != 0) {
            //txChoiceadmin.setBackgroundResource(R.drawable.arrow_up);
            showAccountChoiceWindow();
        }
    }

    private void showAccountChoiceWindow() {
        View view = mInflater.inflate(R.layout.input_selectlist, null);
        RelativeLayout contentview = (RelativeLayout) view.findViewById(R.id.input_select_listlayout);
        ListView userlist = (ListView) view.findViewById(R.id.input_select_list);
        userlist.setDividerHeight(0);

        selectadapter = new SelectListAdapter(getActivity(), userBeanList);
        selectadapter.setOnItemClickListener(this);
        //adapter.setOnDelBtnClickListener(this);
        userlist.setAdapter(selectadapter);

        mSelectWindow = new PopupWindow(contentview, txChoiceadmin.getMeasuredWidth(), ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mSelectWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_input_bottom_normal));
        mSelectWindow.setOutsideTouchable(true);
        mSelectWindow.setFocusable(true);
        mSelectWindow.setOnDismissListener(this);
        mSelectWindow.showAsDropDown(txChoiceadmin, 0, 0);
        //txChoiceadmin.setBackgroundDrawable(R.drawable.arrow_up);
    }
}
